package net.cn_su.sharpeyes.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hik.mcrsdk.rtsp.LiveInfo;
import com.hik.mcrsdk.rtsp.RtspClient;
import com.hikvision.vmsnetsdk.CameraInfo;
import com.hikvision.vmsnetsdk.CameraInfoEx;
import com.hikvision.vmsnetsdk.RealPlayURL;
import com.hikvision.vmsnetsdk.ServInfo;
import com.hikvision.vmsnetsdk.VMSNetSDK;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import net.cn_su.sharpeyes.R;
import net.cn_su.sharpeyes.application.SuApplication;
import net.cn_su.sharpeyes.beans.Camera;
import net.cn_su.sharpeyes.beans.Organization;
import net.cn_su.sharpeyes.dialog.CallFailDialog;
import net.cn_su.sharpeyes.dialog.CallSuccessDialog;
import net.cn_su.sharpeyes.live.CameraAdapter;
import net.cn_su.sharpeyes.live.ConstantLive;
import net.cn_su.sharpeyes.live.LiveCallBack;
import net.cn_su.sharpeyes.live.LiveControl;
import net.cn_su.sharpeyes.pref.ServerInfo_;
import net.cn_su.sharpeyes.utils.BitmapUtils;
import net.cn_su.sharpeyes.utils.NetWorkUtils;
import net.cn_su.sharpeyes.utils.UIUtil;
import net.cn_su.sharpeyes.utils.http.HttpClient;
import net.cn_su.sharpeyes.utils.http.HttpUrl;
import net.cn_su.sharpeyes.utils.http.JacksonMapper;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import cz.msebera.android.httpclient.Header;

@Fullscreen
@EActivity(R.layout.activity_live)
public class LiveActivity extends AppCompatActivity implements LiveCallBack {

    @ViewById
    protected TextView textView_camera, textView_camera_address, textView_organization;
    @ViewById
    protected LinearLayout layout_bottom_normal, layout_bottom_fullscreen, layout_playback, ll_organization, btn_full, btn_exit_full, btn_loginout;
    @ViewById
    protected RelativeLayout layout_right, layout_left;
    @ViewById
    protected ListView listView_camera;
    @ViewById
    protected ProgressBar progressBar;
    @Bean
    protected CameraAdapter cameraAdapter;
    @App
    protected SuApplication suApplication;
    @Pref
    protected ServerInfo_ serverInfo;


    /**
     * 当前摄像头
     */
    private Camera currentCamera = null;
    /**
     * 当前机构
     */
    private Organization currentOrg = null;

    /**
     * 监控点信息对象
     */
    private CameraInfo cameraInfo;
    /**
     * 服务信息
     */
    private ServInfo mServInfo;
    /**
     * 控制层对象
     */
    private LiveControl mLiveControl;
    /**
     * RTSP sdk句柄
     */
    private RtspClient mRtspHandle = null;
    /**
     * 服务器校验时的token
     */
    private String mToken = null;
    /**
     * 码流类型
     */
    private int mStreamType = -1;
    /**
     * 创建消息对象
     */
    private Handler mMessageHandler = new LiveHandler();

    /**
     * 播放视频的控件对象
     */
    @ViewById
    protected SurfaceView mSurfaceView;

    //海康SDK
    private VMSNetSDK mVmsNetSDK = null;

    /**
     * 判断是否第一次进入
     */
    private boolean isRestart = false;
    /**
     * 保存图片的地址
     */
    private final String SAVEPATH = "/sdcard/sharp_eyes/";

    /**
     * 判断视频是否加载成功
     */
    private boolean flag = false;


    private boolean isChangeCamera = false;


    private boolean isLogin = false;
    /**
     * 提示网络连接的对话框
     */
    private AlertDialog mNetDialog;


    /**
     * 右边菜单的宽度
     */
    private int rWidth = 0;
    /**
     * 左边视频的宽度
     */
    private int lWidth;
    /**
     * 屏幕的宽度
     */
    private int dWidth;

    /**
     * 音频是否开启
     */
    private boolean mIsStartAudio = false;
    @Extra
    protected int orgId;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) && NetWorkUtils.isNetworkConnected(LiveActivity.this)) {
             //   Logger.d("网络状态已经改变");
                mNetDialog.dismiss();
                if (currentCamera == null) {

                    mVmsNetSDK = VMSNetSDK.getInstance();
                    mVmsNetSDK.openLog(true);
                    mLiveControl = new LiveControl();
                    mLiveControl.setLiveCallBack(LiveActivity.this);
                    // RTSP SDK
                    mRtspHandle = RtspClient.getInstance();
                    if (null == mRtspHandle) {
                     //   Logger.v("initialize:" + "RealPlay mRtspHandle is null!");
                    }

                    listView_camera.setAdapter(cameraAdapter);
                    // 登录自有平台,有网络的情况下可以执行
                    switchOrg(suApplication.getOrgById(orgId));
                } else {

                    if (null != currentCamera) {
                        if (isLogin) {
                            play(currentCamera);
                        } else {
                            loginHik();
                        }

                    }

                }


            } else {
          //      Logger.d("无网络连接");
                mNetDialog.show();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dWidth = this.getWindowManager().getDefaultDisplay().getWidth();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mNetDialog = NetWorkUtils.getNetworkDialog(this);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);

        Log.v("result",HttpUrl.ROOT);

    }


    @Override
    protected void onStop() {
        super.onStop();
        if (flag && mLiveControl != null && mIsStartAudio) {
            mLiveControl.stopAudio();
        }
        flag = false;
        stopPlay();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (isChangeCamera) {
            isRestart = false;
            isChangeCamera = false;
            return;
        } else {
            isRestart = true;
        }

        if (null != currentCamera) {
        //    Logger.v("onRestart");
            if (NetWorkUtils.isNetworkConnected(this)) {
                showProgressBar();
                if (isLogin) {
                    play(currentCamera);
                } else {
                    loginHik();
                }

            }

        }

    }

    @AfterViews
    protected void init() {

        if (cameraAdapter != null)
            listView_camera.setAdapter(cameraAdapter);


        ll_organization.requestFocus();


    }

    /**
     * 更换显示的摄像头
     *
     * @param camera      摄像头位置
     * @param needRefresh 是否强制刷新
     */
    @UiThread
    protected void switchCamera(Camera camera, boolean needRefresh) {
        if (camera == null) {
            currentCamera = camera;
            layout_playback.setVisibility(View.GONE);
            return;
        }
        if (currentCamera != camera || needRefresh) {
            currentCamera = camera;
            layout_playback.setVisibility(View.VISIBLE);
            textView_camera.setText(" - " + currentCamera.getName());
            textView_camera_address.setText(currentCamera.getAddress());
            showProgressBar();
            if (isLogin) {
                play(currentCamera);
            } else {
                loginHik();
            }

        }
    }

    /**
     * 播放视频
     *
     * @param camera 摄像头位置
     */
    @Background
    protected void play(Camera camera) {
        // 先获取摄像头的扩展信息
        CameraInfoEx cameraInfoEx = new CameraInfoEx();
        boolean result = mVmsNetSDK.getCameraInfoEx(serverInfo.serverAddress().get(), mServInfo.getSessionID(), camera.getCameraId(), cameraInfoEx);
        if (result) {
            // 进入播放程序
            mLiveControl.setLiveParams(getPlayUrl(mStreamType, cameraInfoEx), serverInfo.hikAccount().get(), serverInfo.hikPassword().get());
            if (mLiveControl.LIVE_PLAY == mLiveControl.getLiveState()) {
                mLiveControl.stop();
            }
            if (mLiveControl.LIVE_INIT == mLiveControl.getLiveState()) {
                mLiveControl.startLive(mSurfaceView);
            }
        } else {
            showToast(R.string.error_camerainfoex_load);
        }
    }

    /**
     * 停止播放
     */
    @Background
    protected void stopPlay() {
        try {
            mLiveControl.stop();
        } catch (Exception e) {

        }
    }


    /**
     * 截屏保存
     */
    protected String capturePicture() {
        if (null != mLiveControl) {
            String fileName = getPictureName();
            boolean ret = mLiveControl.capture(SAVEPATH, fileName);
            if (ret) {
                return fileName;
            }
        }
        return null;
    }

    /**
     * @return
     */
    private String getPictureName() {
        return System.currentTimeMillis() + "su_picture.jpg";
    }


    @UiThread
    protected void showToast(int msgId) {
        hideProgressBar();
        UIUtil.showToast(this, msgId);
    }

    /**
     * 隐藏进度条
     */
    @UiThread
    protected void hideProgressBar() {
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 显示进度条
     */
    @UiThread
    protected void showProgressBar() {
        progressBar.setVisibility(View.VISIBLE);
    }

    /**
     * 点击切换摄像头
     *
     * @param position 列表中的位置
     */
    @ItemClick(R.id.listView_camera)
    protected void cameraChoose(int position) {
        if (progressBar.getVisibility() == View.VISIBLE) {
            return;
        }

        cameraAdapter.setSelectedPosition(position);
        cameraAdapter.notifyDataSetChanged();
        // 切换显示摄像头
        switchCamera(cameraAdapter.getItem(position), false);
    }

  /*  *//**
     * 打电话
     *//*
    @Click({R.id.btn_phone})
    protected void btnPhoneClick() {
        if (progressBar.getVisibility() == View.VISIBLE) {
            return;
        }
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(getResources().getString(R.string.dialog_call_phone_tip))
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("拨号", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "6995"));
                        startActivity(intent);
                        dialog.dismiss();
                    }
                })
                .create();
        dialog.show();


    }*/

    /**
     * 火警报警
     */
    @Click({R.id.btn_call_fire, R.id.btn_call_fire_bottom})
    protected void btnCallFireClick() {
        calling(1051);
    }

    /**
     * 刷新
     */
    @Click({R.id.btn_refresh})
    protected void btnRefreshClick() {
        if (null != currentCamera) {
            showProgressBar();
            if (isLogin) {
                play(currentCamera);
            } else {
                loginHik();
            }

        }
    }

    /**
     * 盗窃报警
     */
    @Click({R.id.btn_call_theft, R.id.btn_call_theft_bottom})
    protected void btnCalltheftClick() {
        calling(1053);
    }

    /**
     * 伤害报警
     */
    @Click({R.id.btn_call_hurt, R.id.btn_call_hurt_bottom})
    protected void btnCallHurtClick() {
        calling(1052);
    }

    /**
     * 其他报警
     */
    @Click({R.id.btn_call_other, R.id.btn_call_other_bottom})
    protected void btnCallOtherClick() {
        calling(1054);
    }

    /**
     * 进行报警
     *
     * @param callType 报警类型
     */
    protected void calling(final int callType) {
        if (!flag || progressBar.getVisibility() == View.VISIBLE) {
            return;
        }

        showProgressBar();
        final String fileName = capturePicture();
        RequestParams params = new RequestParams();
        params.add("login", serverInfo.localAccount().get().toString());
        params.add("camera_id", currentCamera.getId() + "");
        params.add("call_type_id", callType + "");
        // 发送报警请求
        HttpClient.post(LiveActivity.this, HttpUrl.CALL_POLICE, params, new JsonHttpResponseHandler() {
            @Override
            public void onStart() {
                showProgressBar();
            }

            @Override
            public void onFinish() {
                hideProgressBar();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                //显示提示框
                final CallSuccessDialog successDialog = new CallSuccessDialog(LiveActivity.this);
                successDialog.show();
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        successDialog.dismiss();
                    }
                }, 2500);

                if (fileName != null) {
                    try {
                        int id = response.getInt("id");
                        uploadCallCapture(id, fileName);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                try {

                    //显示提示框
                    final CallFailDialog filedDialog = new CallFailDialog(LiveActivity.this);
                    filedDialog.show();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            filedDialog.dismiss();
                        }
                    }, 2500);
                    UIUtil.showToast(LiveActivity.this, errorResponse.getString("error_description"));
                } catch (JSONException e) {
                    UIUtil.showToast(LiveActivity.this, R.string.call_police_fail);
                }
            }
        });


    }

    /**
     * 上传报警图片
     *
     * @param id       对应记录ID
     * @param fileName 文件路径
     */
    protected void uploadCallCapture(int id, String fileName) {
        RequestParams params = new RequestParams();
        params.add("id", id + "");

        File file = BitmapUtils.getSmallBitmap(SAVEPATH + fileName);

        try {
            params.put("attachment", file, "image/jpeg");
            HttpClient.post(LiveActivity.this, HttpUrl.UPLOAD_CALL_CAPTURE_PICTURE, params, new TextHttpResponseHandler() {

                @Override
                public void onFinish() {
                    super.onFinish();

                    hideProgressBar();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    upError("报警上传图片失败errorCode==" + statusCode, "报警上传图片");
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                 //   Logger.v("上传成功");

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 点击查看录像
     */
    @Click(R.id.layout_playback)
    protected void playbackClick() {
        if (currentCamera != null) {
            if (!flag) {
                return;
            }
            stopPlay();
            PlayBackActivity_.intent(LiveActivity.this)
                    .extra("cameraID", currentCamera.getCameraId())
                    .extra("cameraName", currentCamera.getName())
                    .extra("cameraAddress", currentCamera.getAddress())
                    .startForResult(2);
        }
    }


    /**
     * 点击切换组织机构按钮
     */
    @Click(R.id.ll_organization)
    protected void orgSwitchClick() {

        stopPlay();
        if (suApplication.getOrganizations() != null) {
            OrgChooseActivity_.intent(LiveActivity.this).startForResult(1);
        }

    }

    /**
     * 点击报警记录按钮
     */
    @Click({R.id.btn_call_back, R.id.rl_call_back})
    protected void callBackClick() {
     /*   if (!flag) {
            return;
        }*/
        stopPlay();
        CallPliceActivity_.intent(LiveActivity.this).start();


    }

    /**
     * 点击报修按钮
     */
    @Click({R.id.btn_baoxiu, R.id.btn_baoxiu2})
    protected void callBaoXiuClick() {

        if (currentCamera != null) {

            BaoXiuActivity_.intent(LiveActivity.this).extra("camera", currentCamera.getName())
                    .extra("camera_id", currentCamera.getId()).start();
        }


    }

    /**
     * 点击修改密码
     */
    @Click({R.id.btn_update_pwd})
    protected void callPwdClick() {
        UpdatePwdActivity_.intent(LiveActivity.this).start();

    }

    /**
     * 获取选择后的机构
     *
     * @param orgId 选中的机构ID
     */
    @OnActivityResult(1)
    void onResult(@OnActivityResult.Extra int orgId) {
      //  Logger.v("onResult");
        if (orgId != -1) {
            // 选择了机构
            isChangeCamera = true;
            Organization org = suApplication.getOrgById(orgId);
            switchOrg(org);
        } else {
            // 点击的返回, 直接播放当前摄像头已使用onrestart
            //   switchCamera(currentCamera, true);
        }
    }

    /**
     * 切换当前机构
     */
    private void switchOrg(Organization org) {
        if (org != null && (currentOrg == null || currentOrg.getId() != org.getId())) {

            if (currentOrg != null) {
         //       Logger.v("currentOrg.getId()==" + currentOrg.getId());
         //       Logger.v("org.getId()==" + org.getId());
            }
            currentOrg = org;
            // 跟换名称显示
            textView_organization.setText(org.getName());
            //刷新摄像头列表
            loadCameras(org);
        } else {
       //     Logger.v("继续播放之前选中的摄像头");
            // 继续播放之前选中的摄像头
            switchCamera(cameraAdapter.getSelectedCamera(), true);
        }
    }

    /**
     * 加载机构下的摄像头点位
     */
    protected void loadCameras(Organization org) {
        showProgressBar();
        // 去服务器加载摄像头点位

        RequestParams params = new RequestParams();
        params.add("organization_id", org.getId() + "");
        HttpClient.get(HttpUrl.LOAD_CAMERAS, params, new JsonHttpResponseHandler() {
            @Override
            public void onStart() {
                showProgressBar();
            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    // 保存摄像头信息
                    List<Camera> cameras = JacksonMapper.parseToList(response.getString("cameras"), new TypeReference<List<Camera>>() {
                    });

                    cameraAdapter.setCameras(cameras);
                    cameraAdapter.setSelectedPosition(0);
                    cameraAdapter.notifyDataSetInvalidated();

                    if (cameras.size() > 0) {


                        if (currentCamera != cameras.get(0)) {
                            currentCamera = cameras.get(0);
                            layout_playback.setVisibility(View.VISIBLE);
                            textView_camera.setText(" - " + currentCamera.getName());
                            textView_camera_address.setText(currentCamera.getAddress());
                            showProgressBar();


                      //      Logger.d("进来了---");
                            if (!isRestart) {
                         //       Logger.d("进来了++");
                                if (isLogin) {
                                    play(currentCamera);
                                } else {
                                    loginHik();
                                }

                            }
                            //   进入onrestart刷新
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                UIUtil.showToast(LiveActivity.this, R.string.load_camera_fail);
            }
        });
        //   switchCamera(currentCamera, false);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && rWidth == 0) {
            rWidth = layout_right.getWidth();
            mSurfaceView.getLayoutParams().width = dWidth - rWidth;
            layout_left.setLayoutParams(mSurfaceView.getLayoutParams());
            mSurfaceView.setLayoutParams(mSurfaceView.getLayoutParams());
            lWidth = dWidth - rWidth;

        }
    }

    /**
     * 点击全屏按钮
     */
    @Click(R.id.btn_full)
    protected void inhFullScreen() {
        if (!flag) {
            return;
        }
        // 全屏显示
      /*  layout_right.setVisibility(View.GONE);
        layout_bottom_normal.setVisibility(View.GONE);
        layout_bottom_fullscreen.setVisibility(View.VISIBLE);*/


        layout_bottom_normal.setVisibility(View.GONE);
        layout_bottom_fullscreen.setVisibility(View.VISIBLE);

        layout_left.getLayoutParams().width = dWidth;
        layout_left.setLayoutParams(layout_left.getLayoutParams());
        ValueAnimator valueAnimator = new ValueAnimator();
        valueAnimator.setFloatValues(0, rWidth);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                layout_right.setTranslationX(value);

            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                btn_exit_full.requestFocus();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        valueAnimator.start();
    }

    /**
     * 点击查看政务公开
     */
    @Click(R.id.btn_zhenwu)
    protected void messageClick() {
        stopPlay();
        MessageListActivity_.intent(LiveActivity.this).extra("orgId", orgId)
                .start();

    }

    /**
     * 点击退出登录
     */
    @Click(R.id.btn_loginout)
    protected void loginOutClick() {


        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("是否立即退出登录?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        serverInfo.isLogin().put(false);
                        LoginActivity_.intent(LiveActivity.this).start();
                        stopPlay();
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });


        builder.create().show();


    }

    /**
     * 退出全屏按钮
     */
    @Click(R.id.btn_exit_full)
    protected void exitFullScreen() {
        // 退出全屏
   /* //    layout_right.setVisibility(View.VISIBLE);
        layout_bottom_normal.setVisibility(View.VISIBLE);
        layout_bottom_fullscreen.setVisibility(View.GONE);*/
        //Logger.v("btn_exit_full");
        layout_bottom_normal.setVisibility(View.VISIBLE);
        layout_bottom_fullscreen.setVisibility(View.GONE);
        ValueAnimator valueAnimator = new ValueAnimator();
        valueAnimator.setFloatValues(rWidth, 0);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {

                float value = (float) animation.getAnimatedValue();
                layout_right.setTranslationX(value);


            }
        });
        valueAnimator.start();
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                layout_left.getLayoutParams().width = lWidth;
                layout_left.setLayoutParams(layout_left.getLayoutParams());
                btn_full.requestFocus();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

    }
    // ------------------------------------------------以下是hik demo的code----------------------------------------------


    /**
     * 该方法是获取播放地址的，当mStreamType=2时，获取的是MAG，当mStreamType =1时获取的子码流，当mStreamType = 0时获取的是主码流
     * 由于该方法中部分参数是监控点的属性，所以需要先获取监控点信息，具体获取监控点信息的方法见resourceActivity。
     *
     * @param streamType 2、表示MAG取流方式；1、表示子码流取流方式；0、表示主码流取流方式；
     * @return String 播放地址 ：2、表示返回的是MAG的播放地址;1、表示返回的是子码流的播放地址；0、表示返回的是主码流的播放地址。
     * @since V1.0
     */
    private String getPlayUrl(int streamType, CameraInfoEx cameraInfoEx) {
        String url = "";

        /**
         * 通过VMSNetSDK返回的预览地址对象
         */
        RealPlayURL mRealPlayURL = new RealPlayURL();
        if (mServInfo == null) {
            return null;
        }
        // 获取播放Token
        if (mServInfo.isTokenVerify()) {
            // 获取播放Token
            mToken = mVmsNetSDK.getPlayToken(mServInfo.getSessionID());
        }
        String tag = "HIK";
        //        Log.i(tag, "mToken is :" + mToken);
        //        Log.d(tag, "generateLiveUrl MagStreamSerAddr:" + mServInfo.getMagServer().getMagStreamSerAddr());
        //        Log.d(tag, "generateLiveUrl MagStreamSerPort:" + mServInfo.getMagServer().getMagStreamSerPort());
        //        Log.d(tag, "generateLiveUrl cameraId:" + cameraInfoEx.getId());
        //        Log.d(tag, "generateLiveUrl token:" + mToken);
        //        Log.d(tag, "generateLiveUrl streamType:" + streamType);
        //        Log.d(tag, "generateLiveUrl appNetId:" + mServInfo.getAppNetId());
        //        Log.d(tag, "generateLiveUrl deviceNetID:" + cameraInfoEx.getDeviceNetId());
        //        Log.d(tag, "generateLiveUrl userAuthority:" + mServInfo.getUserAuthority());
        //        Log.d(tag, "generateLiveUrl cascadeFlag:" + cameraInfoEx.getCascadeFlag());
        //        Log.d(tag, "generateLiveUrl internet:" + mServInfo.isInternet());

        LiveInfo liveInfo = new LiveInfo();
        liveInfo.setMagIp(mServInfo.getMagServer().getMagStreamSerAddr());
        liveInfo.setMagPort(mServInfo.getMagServer().getMagStreamSerPort());
        liveInfo.setCameraIndexCode(cameraInfoEx.getId());
        if (mToken != null) {
            liveInfo.setToken(mToken);
        }
        // 转码不区分主子码流
        liveInfo.setStreamType(streamType);
        liveInfo.setMcuNetID(mServInfo.getAppNetId());
        liveInfo.setDeviceNetID(cameraInfoEx.getDeviceNetId());
        liveInfo.setiPriority(mServInfo.getUserAuthority());
        liveInfo.setCascadeFlag(cameraInfoEx.getCascadeFlag());

        //        if (deviceInfo != null) {
        //            if (cameraInfoEx.getCascadeFlag() == LiveInfo.CASCADE_TYPE_YES) {
        //                deviceInfo.setLoginName("admin");
        //                deviceInfo.setLoginPsw("12345");
        //            }
        //        }

        if (mServInfo.isInternet()) {
            liveInfo.setIsInternet(LiveInfo.NETWORK_TYPE_INTERNET);
            // 获取不转码地址
            liveInfo.setbTranscode(false);
            mRealPlayURL.setUrl1(mRtspHandle.generateLiveUrl(liveInfo));

            // 获取转码地址
            // 使用默认转码参数cif 128 15 h264 ps
            liveInfo.setbTranscode(true);
            mRealPlayURL.setUrl2(mRtspHandle.generateLiveUrl(liveInfo));
        } else {
            liveInfo.setIsInternet(LiveInfo.NETWORK_TYPE_LOCAL);
            liveInfo.setbTranscode(false);
            // 内网不转码
            mRealPlayURL.setUrl1(mRtspHandle.generateLiveUrl(liveInfo));
            mRealPlayURL.setUrl2("");
        }

        //        Log.d(tag, "url1:" + mRealPlayURL.getUrl1());
        //        Log.d(tag, "url2:" + mRealPlayURL.getUrl2());

        url = mRealPlayURL.getUrl1();
        if (streamType == 2 && mRealPlayURL.getUrl2() != null && mRealPlayURL.getUrl2().length() > 0) {
            url = mRealPlayURL.getUrl2();
        }
        Log.i(tag, "mRTSPUrl = " + url);

        return url;
    }

    @Override
    public void onMessageCallback(int messageID) {
        sendMessageCase(messageID);
    }

    /**
     * 发送消息
     *
     * @param i void
     * @since V1.0
     */
    private void sendMessageCase(int i) {
        if (null != mMessageHandler) {
            Message msg = Message.obtain();
            msg.arg1 = i;
            mMessageHandler.sendMessage(msg);
        }
    }

    /**
     * 消息类
     *
     * @author huangweifeng
     * @Data 2013-10-23
     */
    @SuppressLint("HandlerLeak")
    private final class LiveHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case ConstantLive.RTSP_SUCCESS:
                    //                    UIUtil.showToast(LiveActivity.this, "启动取流成功");
                    break;

                case ConstantLive.STOP_SUCCESS:
                    //                    UIUtil.showToast(LiveActivity.this, "停止成功");
                    break;

                case ConstantLive.START_OPEN_FAILED:
                    flag = false;
                    //                    UIUtil.showToast(LiveActivity.this, "开启播放库失败");
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    upError("开启播放库失败", getResources().getString(R.string.live_tpye));
                    break;

                case ConstantLive.PLAY_DISPLAY_SUCCESS:
                  /*  if (! mLiveControl.startAudio()){

                    }*/
                    mIsStartAudio = mLiveControl.startAudio();
                    flag = true;
                    //                    UIUtil.showToast(LiveActivity.this, "播放成功");
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    break;

                case ConstantLive.RTSP_FAIL:
                    flag = false;
                    UIUtil.showToast(LiveActivity.this, "RTSP链接失败");
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    if (null != mLiveControl) {
                        mLiveControl.stop();
                    }
                    upError("RTSP链接失败", getResources().getString(R.string.live_tpye));
                    break;

                case ConstantLive.GET_OSD_TIME_FAIL:
                    UIUtil.showToast(LiveActivity.this, "获取OSD时间失败");
                    break;

                case ConstantLive.SD_CARD_UN_USEABLE:
                    UIUtil.showToast(LiveActivity.this, "SD卡不可用");
                    break;

                case ConstantLive.SD_CARD_SIZE_NOT_ENOUGH:
                    UIUtil.showToast(LiveActivity.this, "SD卡空间不足");
                    break;
                case ConstantLive.CAPTURE_FAILED_NPLAY_STATE:
                    UIUtil.showToast(LiveActivity.this, "非播放状态不能抓拍");
                    break;
                case ConstantLive.RECORD_FAILED_NPLAY_STATE:
                    UIUtil.showToast(LiveActivity.this, "非播放状态不能录像");
                    break;
                case ConstantLive.AUDIO_START_FAILED_NPLAY_STATE:
                    UIUtil.showToast(LiveActivity.this, "非播放状态不能开启音频");
                    break;
            }
        }
    }


    /**
     * 上传错误
     */
    private void upError(String errorMessage, String debug_call_name) {

        RequestParams params = new RequestParams();
    //    Logger.d("id==" + serverInfo.userId().get());
        params.add("user_id", serverInfo.userId().get() + "");
        params.add("debug_call_name", debug_call_name);
        params.add("debug_call_content", errorMessage);
        params.add("app_key", "安卓TV端");
        HttpClient.post(LiveActivity.this, HttpUrl.APP_DEBUG_CALL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
       //         Logger.v("日志上传成功");

            }


            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
          //      Logger.v("日志上传失败statusCode==" + statusCode);

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
        //        Logger.v("日志上传失败responseString==" + responseString);
            }
        });
    }


    /**
     * 登录平台
     */
    @Background
    protected void loginHik() {


        final String macAddress = getMacAddr();
        ServInfo servInfo = new ServInfo();
        boolean ret = VMSNetSDK.getInstance().login(serverInfo.serverAddress().get(), serverInfo.hikAccount().get(),
                serverInfo.hikPassword().get(), 1, macAddress, 4, servInfo);
        if (ret) {
            suApplication.setServInfo(servInfo);
            mServInfo = suApplication.getServInfo();


        } else {
            suApplication.setServInfo(null);
        }
        loginHandle(ret);
    }

    /**
     * 登录结果处理
     */
    @UiThread
    protected void loginHandle(boolean success) {


        if (success) {
         //   Logger.v("loginHandle=success=" + UIUtil.getErrorDesc());
            isLogin = true;
            play(currentCamera);
        } else {
            hideProgressBar();
       //     Logger.v("loginHandle==" + UIUtil.getErrorDesc());
            UIUtil.showToast(LiveActivity.this, R.string.login_server_failed);
       //     Logger.d(getString(R.string.login_hik_failed) + UIUtil.getErrorDesc());

            upError(getString(R.string.login_hik_failed) + UIUtil.getErrorDesc(), "海康登录");


        }
    }

    /**
     * 获取登录设备mac地址
     *
     * @return
     */
    protected String getMacAddr() {
        WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        String mac = wm.getConnectionInfo().getMacAddress();
        return mac == null ? "" : mac;
    }
}
